<template>
    <div class="vehicle-dashboard">
        <!-- 第一部分：车辆告警列表 -->
        <div class="alert-section">
            <div class="section-title">车辆告警</div>
            <div class="alert-table">
                <!-- 固定表头 -->
                <div class="alert-header">
                    <div class="alert-col">车牌号</div>
                    <div class="alert-col">告警企业</div>
                    <div class="alert-col">告警内容</div>
                    <div class="alert-col">告警时间</div>
                </div>
                <!-- 滚动内容区 -->
                <div class="alert-list" ref="alertList" @scroll="handleListScroll">
                    <div class="alert-item" v-for="(item, index) in alertData" :key="index"
                        @click="handleCarData(item)">
                        <el-tooltip :content="item.plateNumber" placement="top" :disabled="isScrolling">
                            <div class="alert-col">{{ item.plateNumber }}</div>
                        </el-tooltip>
                        <el-tooltip :content="item.company" placement="top" :disabled="isScrolling">
                            <div class="alert-col">{{ item.company }}</div>
                        </el-tooltip>
                        <el-tooltip :content="item.content" placement="top" :disabled="isScrolling">

                            <div class="alert-col">{{ item.content }}</div>
                        </el-tooltip>
                        <el-tooltip :content="item.time" placement="top" :disabled="isScrolling">

                            <div class="alert-col">{{ item.time }}</div>
                        </el-tooltip>

                    </div>
                </div>
            </div>
        </div>

        <!-- 第二部分：可切换横向柱状图 -->
        <div class="bar-chart-section">
            <div class="section-title">
                车辆分布统计
                <div class="toggle-btn" :class="{ active: currentType === 'industrial' }"
                    @click="toggleType('industrial')">工业园</div>
                <div class="toggle-btn" :class="{ active: currentType === 'district' }" @click="toggleType('district')">
                    行政区</div>
            </div>

            <div class="horizontal-bar">
                <div class="bar-item" v-for="(item, index) in currentBarData" :key="index" @click="moveMap(item)">
                    <el-tooltip :content="item.name" :placement="'top'">
                        <div class="bar-label">{{ item.name }}</div>
                    </el-tooltip>
                    <div class="bar-container">
                        <div class="bar" :style="{ width: item.percentage + '%' }">
                        </div>

                    </div>
                    <div class="bar-value">{{ item.value }}</div>

                </div>
            </div>
        </div>

        <!-- 第三部分：时间变化折线图 -->
        <div class="line-chart-section">
            <div class="section-title">区县内近一周车辆变化趋势</div>
            <div ref="lineChart" style="width: 100%; height: 200px;"></div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { mapMutations, mapActions } from 'vuex'
import { getCarCounts } from '@/api/largescreen/'
import { mapState } from "vuex";

import {
    alarmRecords,
    enterpriseCountsWeekly,
} from "@/api/largescreen/index.js";
export default {
    data() {
        return {
            isScrolling: false,
            // 车辆告警数据
            alertData: [

            ],

            // 柱状图数据
            industrialData: [
                // { name: '工业园1', value: 230 },
                // { name: '工业园2', value: 180 },
                // { name: '工业园3', value: 320 }
            ],
            districtData: [
                // { name: '昌吉市', value: 580 },
                // { name: '阜康市', value: 310 },
                // { name: '呼图壁县', value: 290 },
                // { name: '玛纳斯县', value: 170 }
            ],
            currentBarData: [],
            currentType: 'industrial',

            // 折线图数据
            lineData: {
                xAxis: [],
                // ['5-21', '5-22', '5-23', '5-24', '5-25', '5-26', '5-27'],
                yAxis: [],
                //  [350, 420, 380, 450, 390, 410, 430]
            }
        };
    },

    mounted() {
        // // 初始化折线图
        // this.initAlarm()
        // getCarCounts({ regionType: "qx", district: this.searchRegion.regionName }).then((res) => {
        //     let district = []

        //     res.data.forEach((e) => {

        //         district.push({ name: e.regionName, value: e.total })
        //     })
        //     this.districtData = district

        // })

        // getCarCounts({ regionType: "gyy", district: this.searchRegion.regionName }).then((res) => {
        //     let industrial = []

        //     res.data.forEach((e) => {

        //         industrial.push({ name: e.regionName, value: e.total, geom: e.geoJson })
        //     })
        //     this.industrialData = industrial
        //     this.toggleType('industrial');

        // })
        // this.initLineChart();
        // // 初始化柱状图数据

        // // 监听窗口大小变化，重绘图表
        // window.addEventListener('resize', this.resizeCharts);
    },
    watch: {

        dataScope: {
            immediate: false,
            deep: true,
            handler(newValue, oldValue) {
                this.initAlarm()
                getCarCounts({ regionType: "qx", district: this.searchRegion.regionName }).then((res) => {
                    let district = []

                    res.data.forEach((e) => {

                        district.push({ name: e.regionName, value: e.total })
                    })
                    this.districtData = district

                })

                getCarCounts({ regionType: "gyy", district: this.searchRegion.regionName }).then((res) => {
                    let industrial = []

                    res.data.forEach((e) => {

                        industrial.push({ name: e.regionName, value: e.total, geom: e.geoJson })
                    })
                    this.industrialData = industrial
                    this.toggleType('industrial');

                })
                this.initLineChart();
                // 初始化柱状图数据

                // 监听窗口大小变化，重绘图表
                window.addEventListener('resize', this.resizeCharts);
            }
        }
    },

    beforeDestroy() {
        // 移除事件监听
        window.removeEventListener('resize', this.resizeCharts);
    },
    computed: {
        ...mapState({
            dataScope: (state) => state.map.DataScope,
        }),

        searchRegion() {
            if (this.dataScope.region == 'qz') {
                return {}
            } else {
                let res = this.dataScope.options.find(v => v.value == this.dataScope.region)
                if (res == undefined || res == null) {
                    return
                }
                return { regionName: res.label, regionId: res.value };
            }
        },
    },
    methods: {
        handleListScroll() {
            // 检测到滚动时，设置滚动状态为true
            if (!this.isScrolling) {
                this.isScrolling = true;
            }
            if (this.scrollTimer) {
                clearTimeout(this.scrollTimer);
            }

            // 设置新的计时器，在滚动停止后300ms将isScrolling设为false
            this.scrollTimer = setTimeout(() => {
                this.isScrolling = false;
            }, 300);
        },
        ...mapMutations("map", [
            "SET_SEARCH",
        ]),

        moveMap(data) {
            if (this.currentType === 'industrial') {
                this.$emit('onMoveMap', data.geom);
            }
        },
        handleCarData(data) {
            this.SET_SEARCH({
                show: true,
                carData: data.pid,
            });
        },
        initAlarm() {
            alarmRecords({ districtCode: this.searchRegion.regionId }).then(res => {
                let data = res.data
                this.alertData = res.data.map(v => {
                    return { plateNumber: v.plateNo, company: v.regionName, content: v.alarmReason, time: v.actTime, pid: v.pid }
                })
            })
        },
        // 切换柱状图类型
        toggleType(type) {
            this.currentType = type;
            this.currentBarData = type === 'industrial' ? this.industrialData : this.districtData;
            // 重新计算百分比
            this.currentBarData = this.currentBarData.map(item => {
                item.percentage = (item.value / this.getTotal(type)) * 100;
                return item;
            });
        },

        // 计算总数
        getTotal(type) {
            const data = type === 'industrial' ? this.industrialData : this.districtData;
            return data.reduce((sum, item) => sum + item.value, 0);
        },

        // 初始化折线图
        initLineChart() {
            const lineChartDom = this.$refs.lineChart;
            const myLineChart = echarts.init(lineChartDom);
            enterpriseCountsWeekly({ districtCode: this.searchRegion.regionId }).then((res) => {
                let data = res.data
                const xAxis = []
                const yAxis = []
                data.forEach((element) => {
                    xAxis.push(element.dayTime)
                    yAxis.push(element.total)
                })
                this.lineData.xAxis = xAxis
                this.lineData.yAxis = yAxis
                const option = {
                    tooltip: {
                        trigger: 'axis',
                        backgroundColor: 'rgba(56, 68, 92, 0.9)',
                        borderColor: '#7B61FF',
                        borderWidth: 1,
                        textStyle: { color: '#fff' },
                        // 关键修改：使用 params[0].value 获取数值
                        formatter: (params) => {
                            return `${params[0].name}：<br/>车辆数：${params[0].value}`;
                        }
                    },

                    backgroundColor: 'transparent',
                    grid: { top: 30, bottom: 20, left: 80, right: 20 },
                    xAxis: {
                        type: 'category',
                        data: this.lineData.xAxis,
                        axisLine: { color: '#fff' },
                        axisTick: { color: '#fff' },
                        textStyle: { color: '#fff' }
                    },
                    yAxis: {
                        type: 'value',
                        axisLine: { color: '#fff' },
                        axisTick: { color: '#fff' },
                        textStyle: { color: '#fff' },

                    },
                    series: [{
                        data: this.lineData.yAxis, // 保持数值数组格式
                        type: 'line',
                        color: '#7B61FF',
                        lineStyle: { width: 2 },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0, y: 0, x2: 0, y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgba(123, 97, 255, 0.4)'
                                }, {
                                    offset: 1, color: 'rgba(123, 97, 255, 0)'
                                }]
                            }
                        }
                    }]
                };

                myLineChart.setOption(option);
                this.$lineChart = myLineChart;
            })

        },

        // 窗口大小变化时重绘图表
        resizeCharts() {
            if (this.$lineChart) {
                this.$lineChart.resize();
            }
        }
    }
};
</script>

<style scoped>
.vehicle-dashboard {
    width: 100%;
    max-width: 1200px;
    margin: 20px auto;
    padding-bottom: 20px;
    padding-right: 20px;
    padding-left: 20px;

    font-family: 'Microsoft YaHei';
    color: #fff;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    border-bottom: 2px solid #7B61FF;
    padding-bottom: 5px;
    display: flex;
    align-items: center;
}

/* 车辆告警列表 */
.alert-section {
    margin-bottom: 20px;
    background: rgba(56, 68, 92, 0.7);
    border-radius: 8px;
    padding: 15px;
    height: 300px;
    overflow: hidden;
    position: relative;
}

.alert-table {
    width: 100%;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.alert-header {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 2px solid #7B61FF;
    font-weight: bold;
    position: sticky;
    top: 0;
    background: rgba(56, 68, 92, 0.9);
    z-index: 1;
}

.alert-list {
    /* flex: 1; */
    overflow-y: auto;
    margin-top: 10px;
    height: 270px;
}

.alert-item {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    transition: background-color 0.3s;
    /* height: 300px; */
}

.alert-item:hover {
    background: rgba(123, 97, 255, 0.1);
}

.alert-col {
    flex: 1;
    /* max-width: 25%; */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-right: 10px;
}

/* 自定义滚动条 */
.alert-list::-webkit-scrollbar {
    width: 6px;
}

.alert-list::-webkit-scrollbar-track {
    background: rgba(74, 85, 104, 0.7);
    border-radius: 3px;
}

.alert-list::-webkit-scrollbar-thumb {
    background: #7B61FF;
    border-radius: 3px;
}

.alert-list::-webkit-scrollbar-thumb:hover {
    background: #5B41D9;
}

/* 可切换柱状图 */
.bar-chart-section {
    margin-bottom: 20px;
    background: rgba(56, 68, 92, 0.7);
    border-radius: 8px;
    padding: 15px;
    overflow-y: hidden;
    height: 300px;
}

.toggle-btn {
    display: inline-block;
    padding: 5px 15px;
    margin-left: 15px;
    cursor: pointer;
    border: 1px solid #7B61FF;
    border-radius: 4px;
    transition: all 0.3s;
}

.toggle-btn:hover {
    background: rgba(123, 97, 255, 0.2);
}

.toggle-btn.active {
    background: #7B61FF;
    color: #fff;
    font-weight: bold;
}

.horizontal-bar {
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
    height: 200px;
}

.horizontal-bar::-webkit-scrollbar {
    width: 6px;
}

.horizontal-bar::-webkit-scrollbar-track {
    background: rgba(74, 85, 104, 0.7);
    border-radius: 3px;
}

.horizontal-bar::-webkit-scrollbar-thumb {
    background: #7B61FF;
    border-radius: 3px;
}

.horizontal-bar::-webkit-scrollbar-thumb:hover {
    background: #5B41D9;
}

.bar-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    opacity: 0;
    transform: translateX(-20px);
    animation: fadeIn 0.5s forwards;
    animation-delay: calc(var(--i) * 0.1s);
}

@keyframes fadeIn {
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

.bar-item:nth-child(1) {
    --i: 1;
}

.bar-item:nth-child(2) {
    --i: 2;
}

.bar-item:nth-child(3) {
    --i: 3;
}

.bar-item:nth-child(4) {
    --i: 4;
}

.bar-label {
    width: 120px;
    text-align: right;
    margin-right: 15px;
    font-weight: 500;
    overflow: hidden;
    /* 溢出文本显示省略号 */
    text-overflow: ellipsis;
    white-space: nowrap;

}

.bar-container {
    flex: 1;
    height: 25px;
    background: rgba(74, 85, 104, 0.7);
    border-radius: 13px;
    overflow: hidden;
    position: relative;
}

.bar {
    height: 100%;
    background: linear-gradient(90deg, #7B61FF, #5B41D9);
    border-radius: 10px;
    transition: width 0.8s cubic-bezier(0.25, 0.8, 0.25, 1);
    position: relative;
    overflow: hidden;
}

.bar::after {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 50%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
    animation: shine 2s infinite linear;
}

@keyframes shine {
    to {
        left: 150%;
    }
}

.bar-value {
    position: absolute;
    right: 5px;
    color: #fff;
    font-weight: bold;
    line-height: 25px;
}

/* 折线图 */
.line-chart-section {
    background: rgba(56, 68, 92, 0.7);
    border-radius: 8px;
    padding: 15px;
}
</style>